<template>
  <div class="body">
    <van-nav-bar :title="assemblyobj.name" left-arrow @click-left="onClickLeft" />
    <div class="forms">
      <Engine
        :mode="MODE.MOBILE"
        :scene="SCENE.PRODUCT"
        :dataInject="dataInject"
        :nodeInject="nodeInject"
        :bridge="bridge"
        @submit="onSubmit"
        ref="engine"
      >
      </Engine>
    </div>
    <div style="clear: both"></div>
    <!-- <van-divider /> -->
    <div style="text-align: center">
      <van-button type="info" @click="onSubmits" size="small">确认流程</van-button>
    </div>
    <div v-show="showFlow">
      <div class="flow">流程</div>
      <van-steps direction="vertical" :active="0" active-icon="success" active-color="#1989fa">
        <van-step v-for="(item, index) in steps" :key="index">
          <template>
            <div class="stepPage">
              <div class="stepTitle">
                <h3>{{ item.nodeName }}</h3>
                <div>{{ getNodeDes(item) }}</div>
              </div>
              <template v-if="getDefaultType(item)">
                <div class="stepIcon">
                  <template v-if="item.operatorList.length < 3">
                    <div v-for="res in item.operatorList" :key="res.index">
                      <div>
                        <span>{{ res.realName || res.realname }}</span>
                      </div>
                    </div>
                  </template>
                  <template v-if="item.operatorList.length > 2">
                    <div class="showMorePeople">
                      <div v-for="respons in sliceArray(0, 2, item.operatorList)" :key="respons.index">
                        <span>{{ respons.realName || respons.realname }}</span>
                      </div>
                      <div class="all-header">
                        <van-image
                          @click="showMore(item.operatorList, '查看全部')"
                          width="30"
                          height="30"
                          :src="allIcon"
                        >
                        </van-image>
                      </div>
                    </div>
                  </template>
                </div>
              </template>
              <template v-else-if="item.approvalType == 'service'">
                {{item.nodeName}}
              </template>


              <template v-else>
                <!-- 选择范围的人 -->
                <div v-if="selectType(item)">
                  <div class="stepIcon">
                    <template v-if="item.selectUsers && item.selectUsers.length <= 2">
                      <div v-for="res in item.selectUsers" :key="res.index">
                        <div>
                          <span>{{ res.realName || res.realname }}</span>
                        </div>
                      </div>
                    </template>
                    <template v-if="item.selectUsers && item.selectUsers.length > 2">
                      <div class="showMorePeople">
                        <div v-for="respons in sliceArray(0, 2, item.selectUsers)" :key="respons.index">
                          <span>{{ respons.realName || respons.realname }}</span>
                        </div>
                        <div class="all-header">
                          <van-image @click="showMore(item.selectUsers)" width="30" height="30" :src="allIcon">
                          </van-image>
                        </div>
                      </div>
                    </template>
                  </div>
                  <van-image
                    @click="addMangerScope(item, index)"
                    width="50"
                    height="50"
                    class="stepIconFont"
                    :src="addIcon"
                  >
                  </van-image>
                </div>
                <!-- 选择所有人 -->
                <div v-else>
                  <div class="stepIcon">
                    <template v-if="item.selectUsers && item.selectUsers.length <= 2">
                      <div v-for="res in item.selectUsers" :key="res.index">
                        <div>
                          <span>{{ res.realName || res.realname }}</span>
                        </div>
                      </div>
                    </template>
                    <template v-if="item.selectUsers && item.selectUsers.length > 2">
                      <div class="showMorePeople">
                        <div v-for="respons in sliceArray(0, 2, item.selectUsers)" :key="respons.index">
                          <span>{{ respons.realName || respons.realname }}</span>
                        </div>
                        <div class="all-header">
                          <van-image @click="showMore(item.selectUsers)" width="30" height="30" :src="allIcon">
                          </van-image>
                        </div>
                      </div>
                    </template>
                  </div>
                  <van-image @click="addManger(item, index)" width="50" height="50" class="stepIconFont" :src="addIcon">
                  </van-image>
                </div>
              </template>
            </div>
          </template>
        </van-step>
      </van-steps>
      <!-- <van-button type="info" @click="present" :disabled="disableds" class="submit">提交</van-button> -->
    </div>
    <div v-show="showFlow" style="text-align: center; height: 50px">
      <van-button type="info" :loading="onSubmitLoading" @click="onSubmitend" size="small">提交流程</van-button>
    </div>
    <ContactPicker
      :type="1"
      :key="time"
      ref="mychild"
      :visible="visibleContactPicker"
      :approvedby="approvedby"
      :value="value"
      :max="max"
      @confirm="confirm"
      @closePicker="closePicker"
    />
  </div>
</template>
<script>
import {
  Engine,
  MODE,
  SCENE,
  Bridge,
  injectRequest,
  provideRequest,
  NodeStore,
  convert,
} from '@/components/oa/oa-process.umd'
const bridge = new Bridge()
import { post, get, put } from '@/api/request'
import { getAssembles, getPreviewProcess, saveProcessStart, getSelectListByIds, getRoleNotContainsMe } from '@/api/api'
import '@/components/oa/oa-process.css'
import ContactPicker from '@/components/choiceuse/ContactPicker'
import { Dialog } from 'vant'
// import { getAction, deleteAction, putAction, putparamsAction,postAction, httpAction } from '@/api/manage'
import componentLinkage from '@/utils/ComponentLinkage'

export default {
  data() {
    return {
      MODE,
      SCENE,
      nodeInject: new NodeStore(),
      bridge,
      dataInject: {
        getCanvas: () => {
          return this.procFormInfoqueryByIds()
        },
      },
      assemblyobj: {
        name: '',
      },
      steps: [],
      showFlow: false,
      onSubmitLoading: false,
      defaultType: ['START', 'target_originator', 'target_approval', 'target_role', 'target_management'],
      allIcon: require('@/assets/img/icon_quanbu.png'),
      addIcon: require('@/assets/img/btn_tianjia.png'),
      visibleContactPicker: false, //组件是否展示
      time: new Date().getSeconds(), //去缓存
      approvedby: [],
      value: '',
      max: 1, //是否可以选择多个
      nodeSort: '',
      allUserList: [],
    }
  },
  created() {
    this.browserRedirect()
    injectRequest({ post, get, put })
    window.test = this
  },
  mounted() {
    //监听节点变化
    this.procFormInfoqueryByIds()
    var that = this
    bridge.addEventListener('nodes', (nodes) => {
      that.showFlow = false
      that.processDataVo = []
    })

    // console.log(that.$refs.engine, 'that.$refs.engine')
  },
  components: {
    Engine,
    ContactPicker,
  },
  methods: {
    browserRedirect() {
      var sUserAgent = navigator.userAgent.toLowerCase()
      if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
        //跳转移动端页面
        // console.log('跳转移动端页面')
        // this.$router.push({
        //   path: '/mobileapplyForm',
        //   query: { id: this.$route.query.id, fullName: this.$route.query.fullName },
        // })
      } else {
        //跳转pc端页面
        this.$router.push({
          path: '/applyForm',
          query: { id: this.$route.query.id, fullName: this.$route.query.fullName },
        })

        console.log('跳转pc端页面')
      }
    },
    onClickLeft() {
      this.$router.go(-2)
    },
    showMore(item, message) {
      const name = item.map((item) => {
        return item.realName || item.realname
      })
      Dialog({ message: name.toString(), confirmButtonColor: '#1E8DF5' })
    },
    sliceArray(start, end, sliceArray, newArray = []) {
      newArray = sliceArray.slice(start, end)
      console.log(newArray)
      return newArray
    },
    closePicker() {
      this.visibleContactPicker = false
      this.showFlow = true
    },
    confirm(val, selectedList, judge) {
      //关闭
      console.log(val, this.nodeSort, 'val, selectedList, judge')
      if (judge) {
        this.visibleContactPicker = false
        this.showFlow = true
        return
      }
      this.visibleContactPicker = false
      this.steps[this.nodeSort].selectUsers = selectedList.length > 0 ? selectedList : null
      this.showFlow = true
    },
    //范围是否是全公司
    selectType(e) {
      // console.log(e,'范围是否是全公司')
      if (e.properties.actionerRules[0].select && e.properties.actionerRules[0].select[0] !== 'allStaff') {
        return true
      }
      return false
    },
    // 回显默认值数组
    getTargetArr(item, index) {
      if (item.approvalType === 'target_approval') {
        const { approvals } = item.properties.actionerRules[0]
        const list = this.getIdUser(approvals)
        return list
      }
      return item.operatorList
    },
    //是为默认显示的值
    getDefaultType(item) {
      return this.defaultType.includes(item.approvalType)
    },
    addManger(item, index) {
      this.approvedby = []
      this.value = ''
      this.$refs.mychild.getList()
      const actionerRules = item.properties.actionerRules[0]
      //所有人
      this.showFlow = false
      this.visibleContactPicker = true
      this.max = actionerRules.multi ? 9999 : 1
      this.nodeSort = index
      // if (item.selectUsers) {
      this.value = this.getName(item.selectUsers || [])
      this.$refs.mychild.clearList(item.selectUsers || [])
      this.$refs.mychild.getData()
      // }
    },
    addMangerScope(item, index) {
      this.value = ''
      this.showFlow = false
      this.visibleContactPicker = true
      const actionerRules = item.properties.actionerRules[0]
      const selectType = actionerRules.select[0]
      //是否可以选择多人
      this.max = actionerRules.multi ? 9999 : 1
      //如果是角色范围
      if (selectType === 'labels') {
        getRoleNotContainsMe({
          roleId: item.properties.actionerRules[0].range.role[0].roleId,
          userKey: this.steps[0].operatorList[0].userId,
        }).then((res) => {
          this.approvedby = res.result.map((item) => {
            return {
              realname: item.realName,
              id: item.userId,
            }
          })
          this.$refs.mychild.getList()
        })
        // if (item.selectUsers) {
        this.$refs.mychild.clearList(item.selectUsers || [])
        this.value = this.getName(item.selectUsers || [])
        this.$refs.mychild.getData()
        // }
        this.nodeSort = index
        return
      }
      //指定人员范围
      this.approvedby = selectType === 'approvals' ? this.getIdUserId(actionerRules.range.approvals) : []
      this.$refs.mychild.getList()
      this.nodeSort = index
      // if (item.selectUsers) {
      this.value = this.getName(item.selectUsers || [])
      this.$refs.mychild.clearList(item.selectUsers || [])
      this.$refs.mychild.getData()
      // }
      // this.selectItem =
    },
    getName(arr) {
      let name = arr.map((item) => {
        return item.id
      })
      return name.toString()
    },
    //根据多个id匹配找用户信息列表
    getIdUserId(arr) {
      const list = this.allUserList.filter((item) => {
        return arr.includes(item.id)
      })
      return list.map((item) => {
        return {
          realname: item.realName,
          id: item.userId,
        }
      })
    },
    //根据多个id匹配找用户信息列表
    getIdUser(arr) {
      const list = this.allUserList.filter((item) => {
        return arr.includes(item.id)
      })
      return list.map((item) => {
        return {
          realname: item.realName,
          id: item.userId,
        }
      })
    },
    onSubmitend() {
      const isproNo = this.processDataVo.filter((item) => {
        if(item.nodeType == 'SERVICE'){
          return false;
        }
        return item.nodeType !== 'END' ? !item.selectUsers || item.selectUsers.length <= 0 : false
      })
      if (isproNo && isproNo.length > 0) {
        Dialog({ message: '节点信息必填' })
        return
      }
      const formId = this.$route.query.id
      let procFormDatas = [...this.procFormDatas]
      this.processDataVo.forEach((item, index) => {
        // console.log(item,'ss')
        if (item.selectUsers && item.selectUsers.length > 0) {
          this.processDataVo[index].selectUsers = item.selectUsers.map((i) => {
            return {
              userId: i.id || i.userId,
              realName: i.realname || i.realName,
            }
          })
        }
      })
      const processDataVoList = this.processDataVo
      const formType = this.$route.query.formType
      let proObj = {
        formId,
        procFormDatas,
        formType,
        processDataVo: {
          processCode: this.processDataVoId,
          formId: formId,
          nodeDtos: processDataVoList,
        },
      }

      this.onSubmitLoading = true
      saveProcessStart(proObj).then((res) => {
        if (res.code === 200) {
          this.onSubmitLoading = false
          // this.closeCurrent()
          setTimeout(() => {
            this.$router.push('/process/approval/MyTaskNeedToExcute')
          }, 100)
        } else {
          this.onSubmitLoading = false
          Dialog({ message: res.message })

          // this.$message.error('提交失败')
        }
      })
    },
    onSubmits() {
      const nodes = bridge.getDataSource('nodes')
      var node = convert.out(nodes)
      var list = []
      var procFormDatas = []
      componentLinkage.updateInfo(node);
      for (let i = 0; i < node.length; i++) {
        // if (canLinkNode(node, node[i])) {
        // var nid = node[i].colName
        var colName = node[i].props.colName
        var value = node[i].value
        var required = node[i].isRequired
        var type = node[i].type
        var nid = node[i].nid;
        
        if (required == '1' && componentLinkage.isNodeVisible({nodes:node,id:node[i].nid})) {
          var map = {}
          // map[nid] = value
          map.nid = nid;
          map.key = nid
          map.value = value
          map.colName = colName
          list.push(map)
          if (value == '' || value == null || value == undefined) {
            return Dialog({ message: '必填项不能为空' })
          }
        }
        var maps = {}
        // maps[nid] = value
        maps.key = nid
        maps.value = value
        maps.nid = nid;
        maps.colName = colName
        procFormDatas.push(maps)
        // }
      }
      let procFormDatasArr = nodes.map((item) => {
         return {
           colName:item.props.colName,
           value:item.value
         }
      })
      this.procFormDatas = procFormDatas
      this.getPreviewProcessData(procFormDatasArr)
    },
    // 获取用户ID
    getUserIdList(array) {
      let list = []
      array.forEach((i) => {
        if (i.approvalType === 'target_select') {
          const approvals = i.properties.actionerRules ? i.properties.actionerRules[0].select[0] : ''
          if (approvals === 'approvals') {
            list = list.concat(i.properties.actionerRules[0].range.approvals)
          }
        }
        if (i.approvalType === 'target_approval') {
          list = list.concat(i.properties.actionerRules[0].approvals)
        }
      })
      return list
    },
    getUserIdSelectlist(arr) {
      getSelectListByIds({ ids: arr.toString() }).then((res) => {
        this.allUserList = res.result
      })
    },
    getPreviewProcessData(arr) {
      getPreviewProcess({ formId: this.$route.query.id,procFormDatas:arr }).then((res) => {
        if (res.success) {
          let nodeDtosArr = res.result.nodeDtos.filter((item) => item.nodeType != "SERVICE")
          this.showFlow = true
          this.processDataVoId = res.result.processCode
          this.processDataVo = nodeDtosArr
          let newpro = this.processDataVo.map((item) => {
            if (this.defaultType.includes(item.approvalType)) {
              item.selectUsers = item.operatorList
            }
          })

         
          this.steps = nodeDtosArr;
          
          // this.steps = res.result.nodeDtos
          const list = [...nodeDtosArr]
          this.getUserIdSelectlist(this.getUserIdList(list))
        } else {
          // Notify(res.message)
          Dialog({ message: res.message })
        }
      })
    },
    getNodeDes(item) {
      const rangeSelect = {
        labels: '角色',
        approvals: '指定成员',
        allStaff: '全公司',
      }
      if (item.nodeType === 'APPROVER') {
        const num = item.selectUsers ? item.selectUsers.length + '人' : ''
        return num ? num + '审批' : '请选择审批人'
      }
      if (item.nodeType === 'NOTIFIER') {
        const type = rangeSelect[item.approvalType]
        const num = item.selectUsers ? item.selectUsers.length + '人' : ''
        return '抄送人' + num
      }
      // return item.nodeType !== 'END' ? this.stepsList[item.nodeType] : ''
    },
    onSubmit() {},
    // 自定义表单-通过id查询
    procFormInfoqueryByIds() {
      var id = this.$route.query.id
      let par = {
        id: id,
      }
      return getAssembles(par)
        .then((res) => {
          this.assemblyobj = res.result
          res.result.assemblyList.forEach((item) => {
            delete item.value
          })
          return res.result.assemblyList
        })
        .catch((e) => {
          this.formshow = false
        })
    },
  },
}
</script>
<style lang="less">
.forms .layout-node {
  min-height: 100px !important;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #1989fa;
}
</style>
<style lang="less" scoped>
.flow {
  padding-left: 15px;
  /* text-align: center; */
}
.stepIconFont {
  position: absolute;
  right: 30px;
  top: 10%;
}
.van-step--vertical {
  position: relative;
}
.body {
  height: 100vh;
  position: relative;
}
</style>